package com.arvato.minipro.controller.common;

import java.util.Date;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.arvato.minipro.bean.bean_do.wx.VerifyTicketDo;
import com.arvato.minipro.bean.bean_dto.common.Result;
import com.arvato.common.config_bean.WxPlatformConfig;
import com.arvato.common.https.WxMiniproThirdRequestUtil;
import com.arvato.common.redis.RedisUtil;
import com.arvato.common.util.JdomUtil;
import com.arvato.common.wx.crypt.AesException;
import com.arvato.common.wx.crypt.WXBizMsgCrypt;
import com.arvato.minipro.controller.BaseController;
import com.arvato.minipro.service.wx.VerifyTicketService;

/**
 * 
 * @author: smallking
 * 
 * @Descibe:处理微信三方平台授权的事件的Controller
 * 以三方平台的身份为已授权的小程序做事情
 * 
 * @Date: 2018年4月16日  下午2:24:05
 */
@Controller
@RequestMapping(value="/minipro")
public class MiniproThirdController extends BaseController{
	
	private Logger logger = LoggerFactory.getLogger(MiniproThirdController.class);
	
	@Autowired
	private RedisUtil redisUtil;
	
	@Autowired
	private WxMiniproThirdRequestUtil wxRequestUtil;
	
	@Autowired
	private VerifyTicketService verifyTicketService;
	
	@ResponseBody
	@RequestMapping(value="/redis/set")
	public String redisSet(String key, String value) {
		logger.info("key: " + key);
		logger.info("value: " + value);
		redisUtil.set(key, value, 120);
		return "success";
	}
	
	@ResponseBody
	@RequestMapping(value="/redis/get")
	public String redisSet(String key) {
		logger.info("key: " + key);
		String value = redisUtil.get(key);
		return value;
	}
	
	/**
	 * 接收WX每十分钟推送一次的ticket
	 * 加密解密策略：采用SHA + AES的加密策略
	 * 解密：将接收到的POST字符串传入工具类解析出一个XML文件
	 * 加密：调用加密工具类，传入参数，进行加密。
	 * 		 最后将加密后的xml以及加密参数signature timestamp nonce当作get参数 传给微信接口
	 * @param verifyTicketDo
	 * @return
	 * @throws AesException 
	 */
	@ResponseBody
	@RequestMapping(value="/auth")
	public String getVerifyTicket(HttpServletRequest req) throws AesException {
		StringBuffer url = req.getRequestURL();
		// 得到微信推送携带的参数
		// 签名 验证消息没有被中间人篡改过
		String signature = req.getParameter("msg_signature");
		// 时间戳
		String timestamp = req.getParameter("timestamp");
		// 随机字符串 签名用盐
		String nonce = req.getParameter("nonce");
		// post推送的ticket数据
		String postData = super.getRequestStr(req).trim();
		logger.info("访问者URl：" + getIpAddr(req) + " " + url);
		logger.info("URL参数：" + signature + "  " + timestamp + " " + nonce);
		logger.info("post密文：" + postData);
		// 开始解密WX推送数据
		WXBizMsgCrypt wxCryptUtil = new WXBizMsgCrypt(WxPlatformConfig.TOKEN, WxPlatformConfig.MSG_KEY, WxPlatformConfig.WX_APPID);
		String mingwen = wxCryptUtil.decryptMsg(signature, timestamp, nonce, postData);
		logger.info("解密后明文" + mingwen);
		// 解析明文XML 得到所要的值
		Map<String, String> resultMap = JdomUtil.xmlElements(mingwen);
		// 存储在缓存redis缓存中 微信十分钟推送一次component_verify_ticket 设置过期时间为600秒
		redisUtil.set("component_verify_ticket", resultMap.get("ComponentVerifyTicket").toString(), 600);
		VerifyTicketDo verifyTicketDo = new VerifyTicketDo();
		verifyTicketDo.setAppId(resultMap.get("AppId"));
		verifyTicketDo.setInfoType(resultMap.get("InfoType"));
		verifyTicketDo.setComponentVerifyTicket(resultMap.get("ComponentVerifyTicket"));
		verifyTicketDo.setCreateTime(new Date());
		try {
			// 插入ticket
			verifyTicketService.insert(verifyTicketDo);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "success";
	}
	
	/**
	 * 前台界面点击申请授权 获取预授权码
	 * @param req
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/auth/pre/code")
	public Result getPreAuthCode(HttpServletRequest req) {
		Result result = new Result();
		String url = "https://mp.weixin.qq.com/cgi-bin/componentloginpage?"
				+ "component_appid=" + WxPlatformConfig.WX_APPID
				+ "&pre_auth_code=%s"
				+ "&redirect_uri=" + "https://minipro.arvatocrm.cn/arvato/minipro/auth/code"
				+ "&auth_type=3";
		result = wxRequestUtil.getPreAuthCode();
		if(result.getCode() == 200) {
			result.setData(String.format(url, result.getData()));
		}
		return result;
	}
	
	/**
	 * 刷新预授权码
	 * @param req
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/auth/pre/code/refresh")
	public Result refreshPreAuthCode(HttpServletRequest req) {
		Result result = wxRequestUtil.refreshPreAuthCode();
		return result;
	}
	
	/**
	 * 用户授权成功之后的回调URL 
	 * 用于接收authorization_code授权码
	 * 授权码：需要通过授权码 来换取授权令牌
	 * @param req
	 * @return
	 */
	@RequestMapping(value="/auth/code")
	public String getAuthAccessToken(HttpServletRequest req) {
		String authCode = req.getParameter("auth_code");
		logger.info("授权码是：" + authCode);
		if(authCode != null) {
			wxRequestUtil.refreshPreAuthCode();
		}
		// 通过授权码去换取authorizer_access_token和authorizer_refresh_token
		Result result = wxRequestUtil.getAuthAccessToken(authCode);
		// 授权之后 转到前台界面上
		if(result.getCode() == 200) {
			// 授权成功之后 返回到小程序码界面
			return "redirect:/qrcode.html?authorizerAppID=" + result.getData();
		}else {
			return "redirect:/index.html?code=" + result.getCode();
		}
	}
	
	/**
	 * 刷新authorizer_access_token
	 * @param req
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/refresh/token")
	public Result refreshAuthAccessToken(HttpServletRequest req) {
		String authorizerAppID = req.getParameter("authorizerAppID");
		Result result = wxRequestUtil.refreshAuthAccessToken(authorizerAppID);
		return result;
	}
	/**
	 * 获取授权的微信用户信息(小程序的信息 不是小程序所有者的信息)
	 * @param req
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/auther/info")
	public Result getAutherInfo(HttpServletRequest req) {
		String authorizerAppID = req.getParameter("authorizerAppID");
		Result result = wxRequestUtil.getAutherInfo(authorizerAppID);
		return result;
	}
	/**
	 * 获取所有已经授权给本第三方平台的授权方信息
	 * @param req
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/auther/info/all")
	public Result getAutherAll(HttpServletRequest req) {
		Result result = wxRequestUtil.listAutherInfo();
		return result;
	}
	/**
	 * 查询修改更新已授权小程序的服务器域名
	 * @param req
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/web/domain")
	public Result operWebDomain(HttpServletRequest req) {
		String authorizerAppID = req.getParameter("authorizerAppID");
		String action = req.getParameter("action");
		Result result = wxRequestUtil.webDomain(authorizerAppID, action);
		return result;
	}
	
	/**
	 * 查询修改更新已授权小程序的业务服务器域名
	 * @param req
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/work/domain")
	public Result operWorkDomain(HttpServletRequest req) {
		String authorizerAppID = req.getParameter("authorizerAppID");
		String action = req.getParameter("action");
		Result result = wxRequestUtil.workDomain(authorizerAppID, action);
		return result;
	}
	/**
	 * 为小程序提交代码
	 * @param req
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/code/commit")
	public Result codeCommit(HttpServletRequest req) {
		String authorizerAppID = req.getParameter("authorizerAppID");
		String templateId = req.getParameter("templateId");
		Result result = wxRequestUtil.codeCommit(authorizerAppID, templateId);
		return result;
	}
	
	/**
	 * 获取小程序的体验码
	 * @param req
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/qrcode")
	public Result qrCode(HttpServletRequest req) {
		String authorizerAppID = req.getParameter("authorizerAppID");
		Result result = wxRequestUtil.getQRCode(authorizerAppID, "");
		return result;
	}
	
	/** 
	 * 获取授权小程序帐号的可选类目
	 * 该接口可获取已设置的二级类目及用于代码审核的可选三级类目。
	 * @param req
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/category")
	public Result getCategory(HttpServletRequest req) {
		String authorizerAppID = req.getParameter("authorizerAppID");
		Result result = wxRequestUtil.getCategory(authorizerAppID);
		return result;
	}
	
	/**
	 * 获取小程序的第三方提交代码的页面配置（仅供第三方开发者代小程序调用）
	 * @param req
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/pagelist")
	public Result pageList(HttpServletRequest req) {
		String authorizerAppID = req.getParameter("authorizerAppID");
		Result result = wxRequestUtil.getPageList(authorizerAppID);
		return result;
	}
	
	/**
	 * 管理小程序的体验人员
	 * @param req
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/tester")
	public Result tester(HttpServletRequest req) {
		String authorizerAppID = req.getParameter("authorizerAppID");
		String wechatid = req.getParameter("wechatid");
		String action = req.getParameter("action");
		Result result = wxRequestUtil.testerMar(authorizerAppID, wechatid, action);
		return result;
	}
	
	/**
	 * 得到当前第三方平台的所有模板
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/template/list")
	public Result templateList() {
		Result result = wxRequestUtil.getTemplateList();
		return result;
	}
	
	/**
	 * 小程序提交审核
	 * @param req
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/submit/audit")
	public Result commitAudit(HttpServletRequest req) {
		String authorizerAppID = req.getParameter("authorizerAppID");
		Result result = wxRequestUtil.submitAudit(authorizerAppID);
		return result;
	}

	/**
	 * 查询小程序最新提交版本的审核状态
	 * @param req
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/audit/status")
	public Result auditStatus(HttpServletRequest req) {
		String authorizerAppID = req.getParameter("authorizerAppID");
		Result result = wxRequestUtil.getAuditResult(authorizerAppID);
		return result;
	}
	
	/**
	 * 小程序发布
	 * @param req
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/publish")
	public Result publish(HttpServletRequest req) {
		String authorizerAppID = req.getParameter("authorizerAppID");
		Result result = wxRequestUtil.release(authorizerAppID);
		return result;
	}
	
	/**
	 * 新增二维码规则
	 * @param req
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/qrcode/regular/set")
	public Result setQRCodeRegular(HttpServletRequest req) {
		String authorizerAppID = req.getParameter("authorizerAppID");
		Result result = wxRequestUtil.setQRCodeRegular(authorizerAppID);
		return result;
	}
	
	/**
	 * 查询二维码规则
	 * @param req
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/qrcode/regular/get")
	public Result getQRCodeRegular(HttpServletRequest req) {
		String authorizerAppID = req.getParameter("authorizerAppID");
		Result result = wxRequestUtil.getQRCodeRegular(authorizerAppID);
		return result;
	}
	
	/**
	 * 删除二维码规则
	 * @param req
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/qrcode/regular/delete")
	public Result deleteQRCodeRegular(HttpServletRequest req) {
		String authorizerAppID = req.getParameter("authorizerAppID");
		Result result = wxRequestUtil.deleteQRCodeRegular(authorizerAppID);
		return result;
	}
	
	/**
	 * 发布二维码规则
	 * @param req
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/qrcode/regular/publish")
	public Result publishQRCodeRegular(HttpServletRequest req) {
		String authorizerAppID = req.getParameter("authorizerAppID");
		Result result = wxRequestUtil.publishQRCodeRegular(authorizerAppID);
		return result;
	}
	
	/**
	 * 设置小程序“扫普通链接二维码打开小程序”能力
	 * 需要用到校验文件，通过此接口来获取
	 * @param req
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/qrcode/check/file")
	public Result getCheckFile(HttpServletRequest req) {
		String authorizerAppID = req.getParameter("authorizerAppID");
		Result result = wxRequestUtil.getCheckFile(authorizerAppID);
		return result;
	}
	
	
	
}
